package com.maibow.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;

import com.maibow.util.Logger;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class ZipUtils {
    protected static final Logger logger = Logger.getLogger(ZipUtils.class);

    /**
     * 
     * 使用gzip进行压缩
     */
    public static String gzip(String primStr) {
        if (primStr == null || primStr.length() == 0) {
            return primStr;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        GZIPOutputStream gzip = null;
        try {
            gzip = new GZIPOutputStream(out);
            gzip.write(primStr.getBytes("utf-8"));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (gzip != null) {
                try {
                    gzip.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        // return
        // Base64.encodeToString(out.toByteArray(),
        // Base64.NO_WRAP);
        return new BASE64Encoder().encode(out.toByteArray());
    }

    /**
     *
     * <p>
     * Description:使用gzip进行解压缩
     * </p>
     * 
     * @param compressedStr
     * @return
     */
    public static String gunzip(String compressedStr) {
        if (compressedStr == null) {
            return null;
        }
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        ByteArrayInputStream in = null;
        GZIPInputStream ginzip = null;
        byte[] compressed = null;
        String decompressed = null;
        try {
            compressedStr = new String(compressedStr.getBytes("utf-8"), "utf-8");
            // compressed =
            // Base64.decode(compressedStr,
            // Base64.NO_WRAP);
            compressed = new BASE64Decoder().decodeBuffer(compressedStr);
            in = new ByteArrayInputStream(compressed);
            ginzip = new GZIPInputStream(in);
            byte[] buffer = new byte[1024];
            int offset = -1;
            while ((offset = ginzip.read(buffer)) != -1) {
                out.write(buffer, 0, offset);
            }
            decompressed = new String(out.toByteArray(), "UTF-8");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (ginzip != null) {
                try {
                    ginzip.close();
                } catch (IOException e) {
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
        }

        return decompressed;
    }

    /**
     * 使用zip进行压缩
     * 
     * @param str
     *            压缩前的文本
     * @return 返回压缩后的文本
     */
    public static final String zip(String str) {
        if (str == null)
            return null;
        byte[] compressed;
        ByteArrayOutputStream out = null;
        ZipOutputStream zout = null;
        String compressedStr = null;
        try {
            out = new ByteArrayOutputStream();
            zout = new ZipOutputStream(out);
            zout.putNextEntry(new ZipEntry("0"));
            zout.write(str.getBytes());
            zout.closeEntry();
            compressed = out.toByteArray();
            // compressedStr =
            // Base64.encodeToString(compressed,
            // Base64.NO_WRAP);
            compressedStr = new BASE64Encoder().encode(out.toByteArray());
        } catch (IOException e) {
            compressed = null;
        } finally {
            if (zout != null) {
                try {
                    zout.close();
                } catch (IOException e) {
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
        }
        return compressedStr;
    }

    /**
     * 使用zip进行解压缩
     * 
     * @param compressed
     *            压缩后的文本
     * @return 解压后的字符串
     */
    public static final String unzip(String compressedStr) {
        if (compressedStr == null) {
            return null;
        }

        ByteArrayOutputStream out = null;
        ByteArrayInputStream in = null;
        ZipInputStream zin = null;
        String decompressed = null;
        try {
            // byte[] compressed =
            // Base64.decode(compressedStr,
            // Base64.NO_WRAP);
            byte[] compressed = new BASE64Decoder().decodeBuffer(compressedStr);
            out = new ByteArrayOutputStream();
            in = new ByteArrayInputStream(compressed);
            zin = new ZipInputStream(in);
            zin.getNextEntry();
            byte[] buffer = new byte[1024];
            int offset = -1;
            while ((offset = zin.read(buffer)) != -1) {
                out.write(buffer, 0, offset);
            }
            decompressed = out.toString();
        } catch (IOException e) {
            decompressed = null;
        } finally {
            if (zin != null) {
                try {
                    zin.close();
                } catch (IOException e) {
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
        }
        return decompressed;
    }

    public static void main(String[] args) throws Exception {
        /*String s = "[{\"contactName\":\"lxb\",\"contactKey\":\"key1\",\"contacts\":[{\"miniType\":1,\"contact\":\"13845787848\",\"itemCompanyName\":2,\"label\":\"\"}]},{\"contactName\":\"lxb\",\"contactKey\":\"key1\",\"contacts\":[{\"miniType\":1,\"contact\":\"13845787848\",\"itemCompanyName\":2,\"label\":\"\"}]}]";
        System.out.println(s.length() + "");
        String gzp = ZipUtils.gzip(s);
        System.out.println("gzp:" + gzp.length());
        System.out.println("gzp:" + gzp);
        String ungzp = ZipUtils.gunzip(gzp);
        System.out.println("ungzp:" + ungzp.length());
        System.out.println("ungzp:" + ungzp);
        String zip = ZipUtils.zip(s);
        System.out.println("zip:" + zip.length());
        System.out.println("zip:" + zip);
        String unzip = ZipUtils.unzip(zip);
        System.out.println("unzip:" + unzip.length());
        System.out.println("unzip:" + unzip);*/

        String gzip = "H4sIAAAAAAAAA6WRubaiQABEc75icgKgu2kgmKBFNgWkAYFHxtYsPkRxAf3658x8" + "wtykTp2qqKouECvlCjcabBRUw5qpMlBkTWMFBhiBX4VYiKrIEGgwk2AJC1B/FDJR"
                            + "gaIm1zX3+z/hhLjGqTkRQuJRmkOLtKQj4dfHb0SXTwdEzJDQpCYby9GvbNfs0iIL" + "xduwhJc6UgyOx84lVwajXc6Dn5mSw5NRhroRooffjzps0hlU7ulooiVSNLHrKnO3"
                            + "DfpyCw38fJ2O3MKSKr+fVoa0tQN9c++ixXRWyMZzLND39A0r4L9t3x1FdbrgacAV" + "dl5jRqfYOrLhzlFvRFR9PXpLz0Dvkuvx1gqRed75pWQh+jikepJHdJn9sz3lZ3Lb"
                            + "Ddm+XlMVrEnkyDYXA8uWNHum6aCMxHmCzrCU2Z4V91nJ+/meBD7iByunQflMPeR1" + "fDSswhK/ViohLxU4s42S/bafYZA5zIMCKoO2PWCDVnB/aP03/eYNuQnI5IiL3/F7"
                            + "Y+qy61dyR20f+qMMuNfls/tfdDVuBttGnYUp2UzUjf4k/YN4smsbuXDT//XCPG0/" + "9/0ARoRNpEICAAA=";

        String ungzip = ZipUtils.gunzip(gzip);
        System.out.println("ungzip:" + ungzip);
    }
}